//
//  SendWorkOrderAndUploadImageController.m
//  iSee
//
//  Created by 刘琛 on 2019/9/24.
//  Copyright © 2019年 刘琛. All rights reserved.
//

#import "SendWorkOrderAndUploadImageController.h"
#import "LeadPickerView.h"
#import <HXPhotoPicker/HXPhotoPicker.h>
#import "NewHomeWebViewController.h"
#import <AFNetworking/AFNetworking.h>
#import "iSeeNetworkRequest.h"
#import "NetworkAddress.h"
#import "SVProgressHUD.h"

@interface SendWorkOrderAndUploadImageController ()<LDSTPickerViewDelegate,UITextViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,HXCustomNavigationControllerDelegate>

@property (nonatomic, strong) UIView *editv;

@property (nonatomic, strong) UITextView *textView;

@property (nonatomic, strong) UILabel *placeholderLabel;

@property (nonatomic, strong) UIButton *addPic;

@property (nonatomic, strong) NSMutableArray *imageArray;

@property (nonatomic, assign) CGFloat widthSpace;

@property (nonatomic, strong) AFHTTPSessionManager *afSessionManager;

@property (nonatomic, strong) NSMutableArray *imageUrlArray;

@property (nonatomic, strong) NSString *redirectBz;

@property (nonatomic, strong) UIButton *quiteNote;

@property (nonatomic, strong) NSMutableArray *qiuteNoteList;

@property (nonatomic, strong) LeadPickerView *pickerView;

@property (nonatomic, strong) HXPhotoManager *photoManager;

@property (nonatomic, assign) NSInteger photoDownloadCount;

@end

@implementation SendWorkOrderAndUploadImageController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _imageUrlArray = [NSMutableArray array];
    _widthSpace = (kScreenWidth - 70 * 4) / 5.0;
    _imageArray = [NSMutableArray array];
    self.view.backgroundColor =[UIColor whiteColor];
    
    if (_tpye == 1) {
        //转派
        _editv = [[UIView alloc] init];
        if (_zpRemarkFlag) {
            _quiteNote = [[UIButton alloc] initWithFrame:CGRectMake(_widthSpace, 10, kScreenWidth - _widthSpace * 2, 35)];
            [_quiteNote setTitle:@"快捷备注" forState:UIControlStateNormal];
            [_quiteNote setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            _quiteNote.titleLabel.font = [UIFont systemFontOfSize:14];
            _quiteNote.layer.borderWidth = 1;
            _quiteNote.layer.borderColor = [UIColor blackColor].CGColor;
            _quiteNote.layer.cornerRadius = 5;
            [_quiteNote addTarget:self action:@selector(getQuiteNoteListFromServer) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:_quiteNote];
            
            _qiuteNoteList = [NSMutableArray array];
            
            _pickerView = [[NSBundle mainBundle] loadNibNamed:@"LeadPickerView" owner:self options:nil].lastObject;
            _pickerView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - Height_NavBar);
            _pickerView.delegate = self;
        }
        _editv.backgroundColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
        _editv.frame = CGRectMake(0, 50, kScreenWidth, 0);
        [self.view addSubview:_editv];
        self.title = @"任务单转派";
        
        UILabel *beizhu = [[UILabel alloc] initWithFrame:CGRectMake(_widthSpace, 5, kScreenWidth - 10, 20)];
        beizhu.font = [UIFont systemFontOfSize:14];
        beizhu.text = @"备注";
        [_editv addSubview:beizhu];
        
        // 评论 UITextView
        _textView = [[UITextView alloc] initWithFrame:CGRectMake(_widthSpace,30, CGRectGetWidth(_editv.frame) - _widthSpace*2, 120)];
        _textView.backgroundColor = [UIColor colorWithRed:0.9508 green:0.9507 blue:0.9507 alpha:1.0];
        _textView.delegate = self;
        _textView.layer.borderWidth = 1;
        _textView.layer.borderColor = [UIColor colorWithRed:0.4 green:0.4 blue:0.4 alpha:1.0].CGColor;
        _textView.layer.cornerRadius = 5;
        [_editv addSubview:_textView];
        
        // 提示字
        _placeholderLabel = [[UILabel alloc] init];
        _placeholderLabel.frame =CGRectMake(5, 6, CGRectGetWidth(_editv.frame)-15*4, 20);
        _placeholderLabel.text = @"在此编辑您的转派内容!";
        _placeholderLabel.textColor = [UIColor colorWithWhite:0.2 alpha:0.6];
        _placeholderLabel.font = [UIFont systemFontOfSize:12.0];
        _placeholderLabel.enabled = NO; // lable必须设置为不可用
        _placeholderLabel.backgroundColor = [UIColor clearColor];
        [_textView addSubview:_placeholderLabel];
        
        // + pic
        
        //如果有图片
        if ([_zpHdImageFlag isEqualToString:@"1"]) {
            _addPic = [UIButton buttonWithType:UIButtonTypeCustom];
            _addPic.frame = CGRectMake(_widthSpace, CGRectGetMaxY(_textView.frame)+15, 70, 70);
            [_addPic setImage:[UIImage imageNamed:@"main_photo_add"] forState:UIControlStateNormal];
            [_addPic addTarget:self action:@selector(addPicEvent) forControlEvents:UIControlEventTouchUpInside];
            [_editv addSubview:_addPic];
            if (_zpRemarkFlag) {
                
                //            _editv.frame = CGRectMake(0, 50, ScreenWidth, 0);
                _editv.frame = CGRectMake(0, 50, kScreenWidth, CGRectGetMaxY(_addPic.frame)+20);
            }else {
                //            _editv.frame = CGRectMake(0, 10, ScreenWidth, 0);
                _editv.frame = CGRectMake(0, 10, kScreenWidth, CGRectGetMaxY(_addPic.frame)+20);
            }
        }else {
            if (_zpRemarkFlag) {
                _editv.frame = CGRectMake(0, 50, kScreenWidth, CGRectGetMaxY(_textView.frame)+ 120);
            }else {
                _editv.frame = CGRectMake(0, 10, kScreenWidth, CGRectGetMaxY(_textView.frame)+ 120);
            }
        }
        
        UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithTitle:@"转派" style:UIBarButtonItemStylePlain target:self action:@selector(zhuanpaiToServer)];
        self.navigationItem.rightBarButtonItem = right;
        
    }else if (_tpye == 2) {
        
        _editv = [[UIView alloc] initWithFrame:CGRectMake(0, 50, kScreenWidth, 0)];
        _editv.backgroundColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
        [self.view addSubview:_editv];
        //回单
        self.title = @"上传回单图片";
        // + pic
        _addPic = [UIButton buttonWithType:UIButtonTypeCustom];
        _addPic.frame = CGRectMake(_widthSpace, 15, 70, 70);
        [_addPic setImage:[UIImage imageNamed:@"main_photo_add"] forState:UIControlStateNormal];
        [_addPic addTarget:self action:@selector(addPicEvent) forControlEvents:UIControlEventTouchUpInside];
        [_editv addSubview:_addPic];
        _editv.frame = CGRectMake(0, 50, kScreenWidth, CGRectGetMaxY(_addPic.frame)+20);
        //派单上传图片
        UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithTitle:@"上传" style:UIBarButtonItemStylePlain target:self action:@selector(sendHDImages)];
        self.navigationItem.rightBarButtonItem = right;
    }
    
    _afSessionManager = [AFHTTPSessionManager manager];
    
}

#pragma mark - UIbutton event

- (void)addPicEvent
{
    [self.view endEditing:YES];
    if (_imageArray.count >= 3) {
        NSLog(@"最多只能上传3张图片");
    
        [SVProgressHUD showErrorWithStatus:@"最多提交3张照片"];
        
    } else {
        
        
        UIAlertController *sheet = [UIAlertController alertControllerWithTitle:@"请选择操作" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        [sheet addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self selectPictures];
        }]];
        
        [sheet addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
            if (authStatus ==AVAuthorizationStatusRestricted ||//此应用程序没有被授权访问的照片数据。
                
                authStatus ==AVAuthorizationStatusDenied)  //用户已经明确否认了这一照片数据的应用程序访问
            {
                // 无权限 引导去开启
                NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                if ([[UIApplication sharedApplication]canOpenURL:url]) {
                    [[UIApplication sharedApplication]openURL:url];
                }
            }else{
                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                    [self pictureAlternative];
                }
                else
                {
                    NSLog(@"手机不支持相机");
                }
            }
        }]];
        
        [sheet addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        

    }
    
    
}

#pragma mark 九宫格布局
// 9宫格图片布局
- (void)nineGrid
{
    for (UIImageView *imgv in _editv.subviews)
    {
        if ([imgv isKindOfClass:[UIImageView class]]) {
            [imgv removeFromSuperview];
        }
    }
    
    CGFloat width = 70;
    CGFloat heightSpace = 10;
    
    NSInteger count ;
    _imageArray.count > 3 ? (count = 3) : (count = _imageArray.count);
    
    for (int i=0; i<count; i++)
    {
        UIImageView *imgv = [[UIImageView alloc] initWithFrame:CGRectMake(_widthSpace+(width+_widthSpace)*(i%4), (i/4)*(width+heightSpace) + CGRectGetMaxY(_textView.frame)+_widthSpace, width, width)];
        
        imgv.image = _imageArray[i];
        imgv.userInteractionEnabled = YES;
        [_editv addSubview:imgv];
        
        UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
        deleteButton.frame = CGRectMake(width-16, 0, 16, 16);
        [deleteButton setImage:[UIImage imageNamed:@"shanchuPNG"] forState:UIControlStateNormal];
        [deleteButton addTarget:self action:@selector(deleteEvent:) forControlEvents:UIControlEventTouchUpInside];
        deleteButton.tag = 10+i;
        [imgv addSubview:deleteButton];
        
        if (i == _imageArray.count - 1)
        {
            if (_imageArray.count % 4 == 0) {
                _addPic.frame = CGRectMake(_widthSpace, CGRectGetMaxY(imgv.frame) + heightSpace, 70, 70);
            } else {
                _addPic.frame = CGRectMake(CGRectGetMaxX(imgv.frame) + _widthSpace, CGRectGetMinY(imgv.frame), 70, 70);
            }
            
            _editv.frame = CGRectMake(0, 50, kScreenWidth, CGRectGetMaxY(_addPic.frame)+20);
        }
    }
}


// 删除照片
- (void)deleteEvent:(UIButton *)sender
{
    UIButton *btn = (UIButton *)sender;
    [_imageArray removeObjectAtIndex:btn.tag-10];
    
    [self nineGrid];
    
    if (_imageArray.count == 0)
    {
        _addPic.frame = CGRectMake(_widthSpace, CGRectGetMaxY(_textView.frame)+15, 70, 70);
        _editv.frame = CGRectMake(0, 50, kScreenWidth, CGRectGetMaxY(_addPic.frame)+20);
    }
}


#pragma mark 拍照
- (void) pictureAlternative{
    //拍照对象
    UIImagePickerController *mypicker = [[UIImagePickerController alloc] init];
    mypicker.delegate = self;
    mypicker.allowsEditing = NO;
    mypicker.videoQuality = UIImagePickerControllerQualityTypeLow;
    mypicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    mypicker.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:mypicker animated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    [_imageArray addObject:image];
    
    [self nineGrid];
}

// 本地相册选择多张照片
- (void)selectPictures {
    
    _photoManager.configuration.photoMaxNum = 3;
    HXCustomNavigationController *nav = [[HXCustomNavigationController alloc] initWithManager:self.photoManager delegate:self];
    nav.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:nav animated:YES completion:nil];
    
    
}

- (void)photoNavigationViewController:(HXCustomNavigationController *)photoNavigationViewController didDoneAllList:(NSArray<HXPhotoModel *> *)allList photos:(NSArray<HXPhotoModel *> *)photoList videos:(NSArray<HXPhotoModel *> *)videoList original:(BOOL)original {
    
    
    [_imageArray removeAllObjects];
    _photoDownloadCount = photoList.count;
    
    for (HXPhotoModel *model in photoList) {
        [model requestPreviewImageWithSize:PHImageManagerMaximumSize startRequestICloud:^(PHImageRequestID iCloudRequestId, HXPhotoModel *model) {
            // 如果照片在iCloud上会去下载,此回调代表开始下载iCloud上的照片
            // 如果照片在本地存在此回调则不会走
        } progressHandler:^(double progress, HXPhotoModel *model) {
            // iCloud下载进度
            // 如果为网络图片,则是网络图片的下载进度
        } success:^(UIImage *image, HXPhotoModel *model, NSDictionary *info) {
            
            [self.imageArray addObject:image];
        
            [self nineGrid];
            self.photoDownloadCount--;
            
        } failed:^(NSDictionary *info, HXPhotoModel *model) {
            // 获取失败
            self.photoDownloadCount--;
        }];
    }
    
}


#pragma mark LeadPickViewDelegate
- (void)pickerView:(LeadPickerView *)leadPickerView AndSelected:(NSString *) areaId AndTitle:(NSString *) title AndType:(NSInteger) type {
    self.redirectBz = title;
    _textView.text = title;
    _placeholderLabel.text = @"";
    
}

#pragma makr - UITextViewDelegate

- (void)textViewDidChange:(UITextView *)textView
{
    if (textView.text.length == 0) {
        _placeholderLabel.text = @"请输入转派内容";
    } else {
        _placeholderLabel.text = @"";
    }
}


#pragma mark 懒加载
- (HXPhotoManager *)photoManager {
    if (!_photoManager) {
        _photoManager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypePhotoAndVideo];
        _photoManager.type = HXPhotoManagerSelectedTypePhoto;
    }
    return _photoManager;
}

#pragma mark 网络请求

- (void)zhuanpaiToServer {
    self.redirectBz = _textView.text;
    
    if (_shaidan) {
        NSError *error;
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:self.userRowId forKey:@"userId"];
        [dic setObject:self.redirectBz forKey:@"remark"];
        NSData *data = [NSJSONSerialization dataWithJSONObject:[NSDictionary dictionaryWithObject:dic forKey:@"data"]
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
        
        [[NSUserDefaults standardUserDefaults] setObject:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] forKey:@"ShangJiShuaiDan"];
        for (UIViewController *popVC in self.navigationController.childViewControllers) {
            if ([popVC isKindOfClass:[NewHomeWebViewController class]]) {
                [self.navigationController popToViewController:popVC animated:YES];
            }
        }
        
    }else {
        if (_isReceiveAndTransfer) {
            [self batchReceiveAndTransfer:self.userRowId];
        }else {
            [self getReAssign:self.userRowId];
            [self sendImageToServer:@"zp"];
        }
    }
}

- (void)batchReceiveAndTransfer:(NSNumber *) userId {
    
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    if (userId)
    {
        [parmas setValue:userId forKey:@"pgUserId"];
    }
    [parmas setValue:self.billIds forKey:@"orderIds"];
    if (self.redirectBz && self.redirectBz.length > 0) {
        NSString *temp = [self.redirectBz stringByReplacingOccurrencesOfString:@"%" withString:@"%25"];
        [parmas setValue:[temp stringByReplacingOccurrencesOfString:@"&" withString:@"%26"] forKey:@"redirectBz"];
    }
    
    [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@",NMarketMainUrl,ZPReceiveAndTransfer) params:parmas success:^(id object) {
        [SVProgressHUD showSuccessWithStatus:@"转派成功"];
        [self performSelector:@selector(goBackToListView1) withObject:nil afterDelay:1];
    } failure:^(NSError *error) {
        
    }];
    

}


//转派

- (void)getReAssign:(NSNumber *)userId
{
    
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    if (userId)
    {
        [parmas setValue:userId forKey:@"pgUserId"];
    }
    [parmas setValue:self.billIds forKey:@"orderIds"];
    if (self.redirectBz && self.redirectBz.length > 0) {
        NSString *temp = [self.redirectBz stringByReplacingOccurrencesOfString:@"%" withString:@"%25"];
        [parmas setValue:[temp stringByReplacingOccurrencesOfString:@"&" withString:@"%26"] forKey:@"redirectBz"];
    }
    
    [SVProgressHUD showWithStatus:@"正在获取数据..."];
    
    [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@",NMarketMainUrl,ZPMissionReAssign) params:parmas success:^(id object) {
        [SVProgressHUD showSuccessWithStatus:@"转派成功"];
        [self performSelector:@selector(goBackToListView1) withObject:nil afterDelay:1];
    } failure:^(NSError *error) {
        [SVProgressHUD dismiss];
    }];

}

- (void)goBackToListView1
{
    NSArray * array = self.navigationController.viewControllers;
    
    
    for (NSInteger i = array.count-1; i >= 0; i--) {
        UIViewController *ctrl = self.navigationController.viewControllers[i];
        if ([ctrl isKindOfClass:NSClassFromString(@"ZSBWorkOrderListViewController")] || [ctrl isKindOfClass:NSClassFromString(@"NewMissonListController")]) {
            UIViewController *ctrl1 = self.navigationController.viewControllers[i];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"RELOADNEWMISSONLIST" object:nil];
            [self.navigationController popToViewController:ctrl1 animated:YES];
            break;
        }
    }
    
    
}

- (void)getQuiteNoteListFromServer {
    
    
    [_qiuteNoteList removeAllObjects];
    
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:_billIds forKey:@"orderIds"];
    
    [SVProgressHUD setStatus:@"数据加载中"];
    
    [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@",NMarketMainUrl,ZPQuiteNote) params:parmas success:^(id object) {
        for (NSDictionary *dic in object[@"body"][@"zpList"]) {
            [self.qiuteNoteList addObject:dic[@"zpqk"]];
        }
        [self.view endEditing:YES];
        self.pickerView.timeArray = self.qiuteNoteList;
        [self.view addSubview:self.pickerView];
        
        [SVProgressHUD dismiss];
    } failure:^(NSError *error) {
        [SVProgressHUD dismiss];
    }];
    
}

#pragma mark 上传图片接口

- (void)sendHDImages {
    [self sendImageToServer:@"hd"];
}

- (void)sendImageToServer:(NSString *) tpyeStr{
    if (_imageArray.count > 0) {
        [_imageUrlArray removeAllObjects];
        
        NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
        
        
        [parmas setObject:self.billIds forKey:@"orderId"];
        [parmas setObject:tpyeStr forKey:@"zpOrHdFlag"];
        
        NSString *urlStr = [NSString stringWithFormat:@"%@nmarket/upload/UploadImageServelt", NMarketMainUrl];
        
        urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
        if ([tpyeStr isEqualToString:@"hd"]) {
            [SVProgressHUD showWithStatus:@"正在获取数据..."];
        }
        
        [_afSessionManager POST:urlStr parameters:parmas constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            for (int i = 0; i < self.imageArray.count; i++) {
                
                NSData *data = UIImageJPEGRepresentation(self.imageArray[i], .5);
                [formData appendPartWithFileData:data name:[NSString stringWithFormat:@"photos[%d]",i] fileName:[NSString stringWithFormat:@"image%d.png",i] mimeType:@"image/png"];
                
            }
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"%@",urlStr);
            if ([tpyeStr isEqualToString:@"hd"]) {
                [SVProgressHUD dismiss];
            }
            NSMutableDictionary *dic =responseObject;
            if ( [dic[@"code"] integerValue]==200) {
                
                if ([tpyeStr isEqualToString:@"hd"]) {
                    
                    NSDictionary *userInfo = [NSDictionary dictionaryWithObject:dic[@"imageUrlList"] forKey:@"imageUrls"];
                    //获得图片url数组 刷新图片
                    [self.navigationController popViewControllerAnimated:YES];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"GETIMAGEURLSTORESETIMAGES" object:nil userInfo:userInfo];
                    });
                }
            }else {
                [SVProgressHUD showErrorWithStatus:dic[@"message"]];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if ([tpyeStr isEqualToString:@"hd"]) {
                [SVProgressHUD dismiss];
            }
            [SVProgressHUD showErrorWithStatus:@"图片上传失败"];
            NSLog(@"%@",error);
        }];
        
    }
}

- (NSString *)setImageWithString:(UIImage *) image {
    NSData *imageData = UIImageJPEGRepresentation([self imageCompressForSize:image targetSize:CGSizeMake(image.size.width * .15, image.size.height * .15)], 1);
    
    NSString *encodedString = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return encodedString;
}

-(UIImage *)imageCompressForSize:(UIImage *)sourceImage targetSize:(CGSize)size{
    
    UIImage *newImage = nil;
    
    CGSize imageSize = sourceImage.size;
    
    CGFloat width = imageSize.width;
    
    CGFloat height = imageSize.height;
    
    CGFloat targetWidth = size.width;
    
    CGFloat targetHeight = size.height;
    
    CGFloat scaleFactor = 0.0;
    
    CGFloat scaledWidth = targetWidth;
    
    CGFloat scaledHeight = targetHeight;
    
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    
    if(CGSizeEqualToSize(imageSize, size) == NO){
        
        CGFloat widthFactor = targetWidth / width;
        
        CGFloat heightFactor = targetHeight / height;
        
        if(widthFactor > heightFactor){
            
            scaleFactor = widthFactor;
            
        }
        
        else{
            
            scaleFactor = heightFactor;
            
        }
        
        scaledWidth = width * scaleFactor;
        
        scaledHeight = height * scaleFactor;
        
        if(widthFactor > heightFactor){
            
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
            
        }else if(widthFactor < heightFactor){
            
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            
        }
        
    }
    
    UIGraphicsBeginImageContextWithOptions(size, NO, 3.0);
    
    CGRect thumbnailRect = CGRectZero;
    
    thumbnailRect.origin = thumbnailPoint;
    
    thumbnailRect.size.width = scaledWidth;
    
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    if(newImage == nil){
        
        NSLog(@"scale image fail");
        
    }
    
    UIGraphicsEndImageContext();
    
    return newImage;
    
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self.view endEditing:YES];
}



@end
